"""C++ analyzer adapter for the unified interface."""

from __future__ import annotations

import sys
from pathlib import Path
from typing import List

# Add cpp-function-call-tree-mcp to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "cpp-function-call-tree-mcp" / "src"))

try:
    from cpp_analyzer import AnalysisConfig, CppCodeAnalyzer
    CPP_ANALYZER_AVAILABLE = True
except ImportError:
    CPP_ANALYZER_AVAILABLE = False

from .base import LanguageAnalyzer, AnalysisResult, FunctionInfo, CallGraph


class CppAnalyzerAdapter(LanguageAnalyzer):
    """Adapter for the C++ analyzer."""

    def analyze(self, paths: List[Path], **kwargs) -> AnalysisResult:
        """Analyze C++ files using the MCP analyzer."""
        if not CPP_ANALYZER_AVAILABLE:
            raise RuntimeError("C++ analyzer not available")

        # Convert paths to strings
        path_strings = [str(p) for p in paths]

        # Create analysis configuration
        config = AnalysisConfig(
            paths=path_strings,
            recursive=kwargs.get('recursive', True),
            include_source_code=kwargs.get('include_source_code', False),
            use_clang=kwargs.get('use_clang', False),
            compile_commands_path=kwargs.get('compile_commands_path'),
            exclude_functions=kwargs.get('exclude_functions', []),
            root_functions=kwargs.get('root_functions'),
            max_depth=kwargs.get('max_depth', 10),
            include_standard_lib=kwargs.get('include_standard_lib', False),
            include_external=kwargs.get('include_external', False),
            detect_cycles=kwargs.get('detect_cycles', True),
        )

        # Run analysis
        analyzer = CppCodeAnalyzer(config)
        result = analyzer.analyze()

        # Convert to unified format
        unified_functions = []
        for func in result.functions:
            unified_func = FunctionInfo(
                name=func.name,
                full_name=func.full_name,
                namespace=func.namespace,
                class_name=func.class_name,
                return_type=func.return_type,
                parameters=func.parameters,
                line_count=func.line_count,
                source_file=func.source_file,
                start_line=func.start_line,
                end_line=func.end_line,
                language="cpp"
            )
            unified_functions.append(unified_func)

        # Convert call graph
        unified_call_graph = CallGraph()
        for caller, callees in result.call_graph.edges.items():
            for callee in callees:
                unified_call_graph.add_call(caller, callee)

        return AnalysisResult(
            functions=unified_functions,
            call_graph=unified_call_graph,
            cycles=result.cycles,
            statistics=result.statistics,
            language="cpp"
        )

    def get_supported_extensions(self) -> List[str]:
        """Return supported C++ file extensions."""
        return ['.c', '.cpp', '.cxx', '.cc', '.h', '.hpp', '.hxx']

    def get_language_name(self) -> str:
        """Return the language name."""
        return "cpp"